--技能按钮
local SkillMove =  require("app.battleV3.ui.objs.SkillMove")
local Armature = require("app.public.avatar.Armature")
local SkillButton = MClass("SkillButton")
local BranchSkillButton = require("app.battleV3.ui.objs.BranchSkillButton")
local TAP_ZORDER = 11
local BTN_CLICKZORDER = 13
local battleConfig = battle.BattleConfig:getInstance()

local colorCfg = Enums.colorCfg

local colorDisable = cc.c4b(181,181,181,255)

local BUFF_TAG_DAZE = 1
local BUFF_TAG_CHAOS = 2
local BUFF_TAG_SILENCE = 3
local BUFF_TAG_TAUNT = 4
local TAG_CD = 101
local TAG_SKILL_LOOP = 102
local TAG_EFFECT = 103
local table_insert = table.insert
local string_format = string.format
local math_floor = math.floor

function SkillButton:ctor()
    --self.root 默认为根节点
    local panel = self:getChildByName("Panel")
    self:setContentSize(panel:getContentSize())
    self.mAnimationNode = panel

    --分支部分
    self.mBranchSkillPanel = panel:getChildByName("Panel_hunter") --某些技能按下去后有分支技能 或者 有蓄力效果，这个就是按下去后会出现的按钮
    self.mHunterChoose = panel:getChildByName("hunter_choose") --选择分支技能后显示的蓝圈
    self.mTouchWidget = panel:findChild("skill_btn")
    self.mBranchSkillPanel:setTouchEnabled(false)
    --蓄力部分
    self.mXuliPanel = panel:getChildByName("Panel_xuli")
    self.mXuliProgressList = {}
    for i = 1, 9 do
       table_insert(self.mXuliProgressList, self.mXuliPanel:getChildByName(string_format("xuli_%d",i)))
    end
    --ongoing
    self.mOnGoing = panel:findChild("ongoing")

    if cc.isAlive(self.mOnGoing) and self.mOnGoingAction == nil then
        self.mOnGoingAction = cc.CSLoader:createTimeline(Res.SkillOnGoing)
        self.mOnGoing:runAction(self.mOnGoingAction)
        self.mOnGoingAction:gotoFrameAndPause( 0 )
    end

    self.mKnight = panel:findChild("ani_knight")
    if self.mKnightAction == nil then
        self.mKnightAction = cc.CSLoader:createTimeline(Res.SkillOnKight)
        self.mKnight:runAction(self.mKnightAction)
        self.mKnightAction:gotoFrameAndPause( 0 )
    end
    self.mKnight:setVisible(false)

    self.mSkillIconNode = panel:getChildByName("Panel_icon")
    self.skillIconLockBg = self.mSkillIconNode:findChild("Image_black")
    self.mSkillIcon = self.mSkillIconNode:findChild("icon")

    --cd
    self.mCdNode = panel:findChild("Panel_cd")
    self.mCdMask = self.mCdNode:findChild("img_cd")
    self.mCdMask:setVisible(false)
    self.cdSprite = self.mCdNode:getChildByTag(TAG_CD)
    if not self.cdSprite then
        self.cdSprite = cc.ProgressTimer:create( self.mCdMask )
        self.cdSprite:setType( cc.PROGRESS_TIMER_TYPE_RADIAL )
        self.cdSprite:setScaleX(-self.mCdMask:getScaleX())
        self.cdSprite:setScaleY(self.mCdMask:getScaleY())
        self.cdSprite:setMidpoint(cc.p( 0.5, 0.5 ))
        self.cdSprite:setPosition(self.mCdMask:getPosition())
        self.cdSprite:setTag(TAG_CD)
        self.mCdNode:addChild(self.cdSprite, -1)
    end
    self.mCdNum = self.mCdNode:findChild("time")

    --Stars
    self.stars = {}
    self.starIndex = {}
    for i = 1, Constant.BattleComboPointMax do
        local star = {}
        local bgStr = "Panel_star/bg_"..i
        local starStr = "Panel_star/s_"..i
        star.bg = panel:findChild(bgStr)
        star.star = panel:findChild(starStr)
        self.stars[i] = star
    end

    --cost
    self.manaIcon = panel:findChild("Panel_logic/icon_1")
    self.energyIcon = panel:findChild("Panel_logic/icon_2")
    self.rageIcon = panel:findChild("Panel_logic/icon_3")
    self.costNum = panel:findChild("Panel_logic/num")

    self.skillMove = SkillMove.new(panel:findChild("Panel_move"))
    self.restrictedEffectsNode = panel:findChild("stop")
    self.ready = panel:findChild("bg_ready")

    --分支按钮
    self.subSkills = {}
    for i = 1, 3 do
        local subSkillBtn = BranchSkillButton.new(self.mBranchSkillPanel:getChildByName("skill_"..i))
        table_insert(self.subSkills,subSkillBtn)
    end

    --光环技能是否激活的表示
    self.mIsHaloActive = false
    local scheduler = display.newNode()
    self.scheduler = scheduler
    self:addChild(scheduler)

    --add onEnter onExit
    local function onNodeEvent(event)
        if "enter" == event then
            self:onEnter()
        elseif "exit" == event then
            self:onExit()
        end
    end

    self:registerScriptHandler(onNodeEvent)
    self.mTouchWidget:setScale(0.85)
    self.mSkillIconNode:setScale(0.85)
    self.mBranchSkillPanel:setVisible(false)
    self.mHunterChoose:setVisible(false)
    self:setLocalZOrder(0)
    self.mXuliPanel:setVisible(false)
    self:setXiliProgress(0)
	self:init()
end

function SkillButton:showBranchSkills()
    self.mTouchWidget:setScale(1)
    self.mSkillIconNode:setScale(1)
    self.mBranchSkillPanel:setVisible(true)
    self.mHunterChoose:setVisible(true)
    self:setLocalZOrder(BTN_CLICKZORDER)
end

function SkillButton:hideBranchSkills(skillId)
    if skillId and skillId == self.skillId and self.skill then
        self.mTouchWidget:setScale(0.85)
        self.mSkillIconNode:setScale(0.85)
        self.mBranchSkillPanel:setVisible(false)
        --无论有没有放出子技能 此处不用管CD的问题
        self:setLocalZOrder(self.originalZOrder)
        self.mHunterChoose:setVisible(false)
    end
end

function SkillButton:setXiliProgress(val)
    for k,v in ipairs(self.mXuliProgressList) do
        v:setVisible(k <= val)
    end
end

function SkillButton:onEnter()

end

function SkillButton:getName()
    return self.name or ""
end

function SkillButton:getIcon()
    return self.icon or ""
end

function SkillButton:getDes()
    return self.desc or ""
end

function SkillButton:onExit()
    self.mCdNode:setVisible(false)
    if self.mSkillLoopNode then
        self.mSkillLoopNode:removeFromParent()
    end
    if self.mAction then
        self.mAction:gotoFrameAndPause(0)
    end

    if cc.isAlive(self.effectArmature) then
        self.effectArmature:removeFromParent()
        self.effectArmature = nil
    end
    self:unregisterScriptHandler()

    if self.lianxieEffect then
        self.lianxieEffect:removeFromParent()
        self.lianxieEffect = nil
    end

    if self.mSkillGuideNode then
        self.mSkillGuideNode:removeFromParent()
        self.mSkillGuideNode = nil
    end
    self:setStar(0, true, 0)

    self.mTouchWidget:setScale(0.85)
    self.mSkillIconNode:setScale(0.85)
    self.mBranchSkillPanel:setVisible(false)
    self.mHunterChoose:setVisible(false)
    self:setLocalZOrder(0)
    self.mXuliPanel:setVisible(false)
    self:setXiliProgress(0)
end

function SkillButton:resetXuliPanel()
    self.mXuliPanel:setVisible(false)
    self:setLocalZOrder(self.originalZOrder)
    self:setXiliProgress(0)
end

function SkillButton:addLoopAni()
    self.mSkillLoopNode = self:getChildByTag(TAG_SKILL_LOOP)
    if not self.mSkillLoopNode then
        self.mSkillLoopNode = cc.CSLoader:createNode(Res.BattleSkillLoopEffect,false,true)
        self.mSkillLoopNode:setTag(TAG_SKILL_LOOP)
        self:addChild(self.mSkillLoopNode)
    end

    if self.mSkillLoopAction == nil then
        self.mSkillLoopAction = cc.CSLoader:createTimeline(Res.BattleSkillLoopEffect)
        if self.mSkillLoopAction then
            self.mSkillLoopNode:runAction(self.mSkillLoopAction)
            self.mSkillLoopAction:gotoFrameAndPlay(0, self.mSkillLoopAction:getDuration(), true)
        end
    end
end

function SkillButton:addSkillGuideNode()
    if not self.mSkillGuideNode then
        self.mSkillGuideNode = cc.CSLoader:createNode(Res.SkillGuideNode,false,true)
        self.mSkillGuideNode:setScale(0.35)
        self:addChild(self.mSkillGuideNode)
        self.mSkillGuideNode:setVisible(false)
    end

    if not self.mSkillGuideAction then
        self.mSkillGuideAction = cc.CSLoader:createTimeline(Res.SkillGuideNode)
        if self.mSkillGuideAction then
            self.mSkillGuideNode:runAction(self.mSkillGuideAction)
            self.mSkillGuideAction:gotoFrameAndPlay(0, self.mSkillGuideAction:getDuration(), true)
        end
    end
end

function SkillButton:playOnGoing()
    if cc.isAlive(self.mOnGoingAction) then
        self.mOnGoingAction:gotoFrameAndPlay(0, self.mOnGoingAction:getDuration(), false)
    end
end


function SkillButton:playHaloActive(isActive)
    self.mKnight:setVisible(isActive)
    if cc.isAlive(self.mKnightAction) then
        if isActive then
            self.mKnightAction:gotoFrameAndPlay(0, self.mKnightAction:getDuration(), true)
        else
            self.mKnightAction:gotoFrameAndPause(0)
        end
    end
end


function SkillButton:showCoreBonus(id,bShow)
    if not (self.skillCfg and self.skillCfg:getSCore()) then
        return
    end

    self.guildTable = self.guildTable or {}
    self.guildTable[id] = bShow

    self.bShowCoreBonus = false
    for _,show in pairs(self.guildTable) do
        if show then
            self.bShowCoreBonus = true
            break
        end
    end
end

function SkillButton:init()
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.SKILL_SETCOST,handler(self,SkillButton.setCostById))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.SKILL_COREBONUS,handler(self,SkillButton.showCoreBonus))
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.SKILL_HIDE_REPLACE_BTN,handler(self,SkillButton.hideBranchSkills))
    BattleUIEvent:addObjToFrameUpdate(self,SkillButton.updateFrame)

   self.originalZOrder = self:getLocalZOrder()

    self.effectArmature = self:getChildByTag(TAG_EFFECT)
    if not self.effectArmature then
        self.effectArmature = Armature.create({path=Res.SkillButtonPreEffectPath,armatureName=Res.SkillButtonPreEffectName,animationName="",skeletonName=Res.SkillButtonPreEffectName})
        self:addChild(self.effectArmature, 9999)
        self.effectArmature:setScale(0.8)
    end
    self.effectArmature:setVisible(false)
    self:initTouch()
end

function SkillButton:playPreEffect()
    if cc.isAlive(self.effectArmature) then
        if not self.effectArmature:isVisible() then
            self.effectArmature:setVisible(true)
            self.effectArmature:playAni({
                name = "loop",
            })
        end
    end
end

function SkillButton:playRleaseEffect()
    if cc.isAlive(self.effectArmature) then
        self.effectArmature:setVisible(true)
        self.effectArmature:stop()
        self.effectArmature:playAni(
            {
                name = "dead",
                playTimes = 1,
                completeCallback = function(sender)
                    if cc.isAlive(self.effectArmature) then
                        self.effectArmature:setVisible(false)
                    end
                end
            })
    end
end

function SkillButton:setStar(num,bLock,consumeComboPointMax)
    -- 1--5
    self.starIndex = {}
    self.needStar = num
    if bLock then
        --1  3
        --2  2  4
        --3  2 3 4
        for i = 1, Constant.BattleComboPointMax do
            local cfg = self.stars[i]
            cfg.star:setVisible(false)
            cfg.bg:setVisible(false)
        end

        if 1 == num then
            self.stars[3].bg:setVisible(true)
            self.starIndex[1] = self.stars[3].star
        elseif 2 == num then
            self.stars[2].bg:setVisible(true)
            self.starIndex[1] = self.stars[2].star
            self.stars[4].bg:setVisible(true)
            self.starIndex[2] = self.stars[4].star
        elseif 3 == num then
            self.stars[2].bg:setVisible(true)
            self.starIndex[1] = self.stars[2].star
            self.stars[3].bg:setVisible(true)
            self.starIndex[2] = self.stars[3].star
            self.stars[4].bg:setVisible(true)
            self.starIndex[3] = self.stars[4].star
        end
    else
        self.needStar = 1
        if consumeComboPointMax == 0 or consumeComboPointMax == Constant.BattleComboPointMax then
            for i = 1, Constant.BattleComboPointMax do
                local cfg = self.stars[i]
                cfg.star:setVisible(false)
                cfg.bg:setVisible(true)
                self.starIndex[i] = cfg.star
            end
        else
            for i = 1, Constant.BattleComboPointMax do
                local cfg = self.stars[i]
                cfg.star:setVisible(false)
                cfg.bg:setVisible(false)
            end

            if 1 == consumeComboPointMax then
                self.stars[3].bg:setVisible(true)
                self.starIndex[1] = self.stars[3].star
            elseif 2 == consumeComboPointMax then
                self.stars[2].bg:setVisible(true)
                self.starIndex[1] = self.stars[2].star
                self.stars[4].bg:setVisible(true)
                self.starIndex[2] = self.stars[4].star
            elseif 3 == consumeComboPointMax then
                self.stars[2].bg:setVisible(true)
                self.starIndex[1] = self.stars[2].star
                self.stars[3].bg:setVisible(true)
                self.starIndex[2] = self.stars[3].star
                self.stars[4].bg:setVisible(true)
                self.starIndex[3] = self.stars[4].star
            end
        end
    end
end

function SkillButton:lightStar(num)
    self.haveStar = num
    --local num  = num<#self.starIndex and num or #self.starIndex
    for i = 1, #self.starIndex do
        local star = self.starIndex[i]
        local bShine = num>=i and true or false
        star:setVisible(bShine)
    end
end

function SkillButton:setSkillEnable(bEnable)
    self.bSkillEnable = bEnable
    self.skillIconLockBg:setVisible(not bEnable)
    self.mSkillIcon:setEnabled(bEnable) --gray image
    if self.costIcon then
        self.costIcon:setEnabled(bEnable)
    end

    if self.costNum:isVisible() then
        if bEnable then
            self.costNum:getVirtualRenderer():setColor(self.costNumColor or colorCfg.mana)
        else
            self.costNum:getVirtualRenderer():setColor(colorDisable)
        end
    end
end

function SkillButton:getCostNumColor(kind)
    if self.bSkillEnable then
        return self.costNumColor
    else
        return colorDisable
    end
end

function SkillButton:setCost(kind,costNum)
    if cc.isDead(self.root) or cc.isDead(self.costNum) or cc.isDead(self[kind.."Icon"]) then
        return
    end
    if costNum and costNum>0 then
        self[kind.."Icon"]:setVisible(true)

        self.costNum:setString(tostring(math.floor(costNum/100)))
        self.bCost = true
        if not self.costNumColor then
            self.costNumColor = colorCfg[kind]
        end
        self.costNum:getVirtualRenderer():setColor(self:getCostNumColor(kind))
        self.costIcon = self[kind.."Icon"]
    else
        self[kind.."Icon"]:setVisible(false)
    end
    self.costNum:setVisible(self.bCost)
end

function SkillButton:setCostById(id)
    if id and id == self.skillId and self.skill then
        self.isSetCost = true
        self:setCost("mana",self.skill:manaCost())
        self:setCost("rage",self.skill:rageCost())
        self:setCost("energy",self.skill:energyCost())

        if self.skill:manaCost() == 0 and
                self.skill:rageCost() == 0 and
                self.skill:energyCost() == 0 then
            self.costNum:setVisible(false)
        else
            self.costNum:setVisible(true)
        end
    end
end

--是否是蓄力技能
function SkillButton:isStoringForceSkill()
    if self.skillCfg and self.skill then

        if self.skillCfg:getIsChantCanCharge() then
            local chantChargeTime = 0
            return true, self.skill:chantD()
        end
    end
    return false, 0
end

--是否是需要选择分支技能
function SkillButton:isNeedChooseBranchSkill()
    if self.skillCfg then
        return self.skillCfg:getChannelType() == Enums.ChannelType.ChannelType_Select_By_Command
    end
    return false
end

--是否是光环技能
function SkillButton:isHaloSkill()
    if self.skillCfg then
        return self.skillCfg:getChannelType() == Enums.ChannelType.ChannelType_Switch_By_Select
    end
    return false
end


function SkillButton:initTouch()
    local function touchEvent(sender, eventType)
        if eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
            --print("ccui.TouchEventType.ended")
            self.startTime = nil
            self.bShowTips = false
            app:dispatchCustomEvent("EVENT_CLOSE_FLOAT")
        elseif eventType == ccui.TouchEventType.began then
            self.startTime = app.session:getServerTime() or app:getUTCTime()
        end
    end
    self.mAnimationNode:addTouchEventListener(touchEvent)
end

function SkillButton:setData(data)
    --self:setStar(2,true)
    --self:lightStar(1)
    if not data then return end
    self.classSkillId = data.classSkillId
    self.skillCfg     = data.skillCfg
    self.skillLv      = data.level
    local oldSkillId = self.skillId
    self.skillId =  self.skillCfg:getId()
    self.comboPointCost  = self.skillCfg:getComboPointCost(self.skillLv)
    self.isLock = self.skillCfg:getConsumeAllComboPoint(self.skillLv)
    self.consumeComboPointMax = self.skillCfg:getConsumeComboPointMax(self.skillLv)
    local isSelectSubSkill = self:isNeedChooseBranchSkill() --是否有分支技能
    local isStoringForceSkill,chantMaxTime = self:isStoringForceSkill() --是否是蓄力技能
    self.chantMaxTime = chantMaxTime
    self.isXuliTouch = false

    --重置一下xulipanel 同时也会还愿button的Order
    self:resetXuliPanel()
    self.mBranchSkillPanel:setVisible(false)
    self.mHunterChoose:setVisible(false)
    self:playHaloActive(false)

    --如果有分支技能 需要初始化分支按钮
    if isSelectSubSkill then
        local subSkillIds =self.skillCfg:getChannel()
        --local subSkillIds = {42043402,42043403,42043404}
        for k, v in ipairs(subSkillIds) do
            self.subSkills[k]:setData({skillCfg = battleConfig:getSkillConfig(v),rootSkillId = self.skillId})
        end
    end

    --如果skillid变化了，需要重新设置color
    if oldSkillId ~= self.skillId then
        self.isSetCost = false
        self.costNumColor = nil
        self.skill = nil
        self.bCost = false
        self.costNum:setVisible(false)
    end

    self:setCostById(self.skillId)

    self:setStar(self.comboPointCost,not self.isLock,self.consumeComboPointMax)
    self.bBusy = false
    self.defaultPos = nil
    local touchBeganPos
    local touchMovedPos
    local touchEndPos
    local function clickCallBack(sender,eventType)
        local isTargetPointSkill = self.skillCfg:isTargetKindPoint()
        local attackRange = self.skillCfg:getRange()
        local maxMovePixel = 110
        local damageRange = self.skillCfg:getDamageRange()

        if eventType == ccui.TouchEventType.began then
            self.bShowTips = false
            self.startTime = app.session:getServerTime() or app:getUTCTime()
            BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.BATTLE_CANCEL_AUTO)
            self.bBusy = true
            self:setLocalZOrder(TAP_ZORDER)
            if isTargetPointSkill then
                --如果是点目标，需要获取优先目标作为特效显示的点
                touchBeganPos = sender:getTouchBeganPosition()
                if self.skill then
                    local pos = self.skill:getTargetPointPriorityTargetPos()
                    self.defaultPos = pos
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_EFFECT,{damageRange = damageRange, moveDis = 0, pos = pos})
                else
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_EFFECT,{damageRange = damageRange, moveDis = 0})
                end

                self.skillMove:setNormalKill(false)
            elseif isSelectSubSkill and self.bSkillEnable then
                --显示子技能
                if self.mBranchSkillPanel:isVisible() then
                    self:hideBranchSkills(self.skillId)
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_HIDE_REPLACE_BTN,self.skillId)
                else
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_SHOW_REPLACE_BTN,self.skillId)
                    self:showBranchSkills()
                    for k, v in ipairs(self.subSkills) do
                        v:playerAni()
                    end
                end
            elseif isStoringForceSkill and self.bSkillEnable then
                --如果是吟唱蓄力技能 则需要显示蓄力panel
                BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_SHOW_XULI_BTN)
                self.mXuliPanel:setVisible(true)
                self:setLocalZOrder(BTN_CLICKZORDER)
                --此时就需要释放技能了
                local tempX, tempY = self:getPosition()
                local posX, posY = self:getParent():toWorldPosition(tempX, tempY)
                BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_SELECT, {skillId = self.skillId, posX = posX})
                self.isXuliTouch = true
            end

        elseif eventType == ccui.TouchEventType.moved then
            if isTargetPointSkill then
                self.defaultPos = nil
                --特效移动
                touchMovedPos = sender:getTouchMovePosition()
                if touchBeganPos ~= nil then
                    local disX = touchMovedPos.x - touchBeganPos.x
                    disX = math.clamp(disX, -maxMovePixel, maxMovePixel)
                    local movePercent = disX/maxMovePixel
                    local moveDis = attackRange * movePercent
                    self.skillMove:setMove(disX)
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_EFFECT,{damageRange = damageRange, moveDis = moveDis})
                end
            end
        elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then
            -- --如果在取消按钮内，则取消
            self.duleTime = app.session:getServerTime() or app:getUTCTime()
            self.skillMove:setVisible(false)

            local isCancel =  self.skillMove:checkCancel(sender:getTouchEndPosition())
            if not isSelectSubSkill then
                self:setLocalZOrder(self.originalZOrder)

                if isTargetPointSkill then
                    --TODO 判断是否在取消按钮内
                    if isCancel then
                        BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_HIDEEFFECT)
                    else
                        --释放技能
                        touchEndPos = sender:getTouchEndPosition()
                        local disX = touchEndPos.x - touchBeganPos.x
                        disX = math.clamp(disX, -maxMovePixel, maxMovePixel)
                        local movePercent = disX/maxMovePixel
                        local moveDis = attackRange * movePercent
                        -- local movePercent = -50
                        -- local moveDis = attackRange * movePercent/100
                        local skillId       =   self.skillCfg:getId()
                        local pos = self.defaultPos
                        BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_RLSEFFECT,{skillId = skillId, damageRange = damageRange, moveDis = moveDis, pos = pos})
                        self.defaultPos = nil
                    end
                elseif isStoringForceSkill then
                    --此时需要结束吟唱
                    --判断技能是否结束吟唱
                    BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_HIDE_XULI_BTN)
                    self:resetXuliPanel()
                    if self.isXuliTouch and self.skill:getChantChargeTime() < chantMaxTime then
                        BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_FINISH_CHANT_CHARGE,{skillId = self.skillId})
                    end
                else
                    if eventType == ccui.TouchEventType.ended then
                        if self.startTime then
                            local tempX, tempY = self:getPosition()
                            local posX, posY = self:getParent():toWorldPosition(tempX, tempY)
                            local skillId = self.skillCfg:getId()
                            if self.duleTime - self.startTime < Constant.BattleCancelInterval then
                                BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_SELECT, {skillId = skillId, posX = posX})
                            end
                        end
                    end
                end
            end


            self.bBusy = false
            self.startTime = nil
            self.bShowTips = false
            self.isXuliTouch = false
            app:dispatchCustomEvent("EVENT_CLOSE_FLOAT")
        end
    end
    self.mTouchWidget:addTouchEventListener(clickCallBack)

    self:loadSkillAppearance()
end


function SkillButton:updateFrame()
    -- 新手战不需要显示tips
    if not app:isBattleGuideComp() then
        return
    end

    if self.isXuliTouch and not self.bSkillEnable then
        if self.skill then
            local chantTime = self.skill:getChantChargeTime()
            --print(chantTime,self.chantMaxTime)
            if chantTime >= self.chantMaxTime then
                BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_HIDE_XULI_BTN)
                self:resetXuliPanel()
                --BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.SKILL_FINISH_CHANT_CHARGE,{skillId = self.skillId})
                self.isXuliTouch = false
            else
                self:setXiliProgress(math_floor(chantTime/self.chantMaxTime * 10))
            end
        end
    else
        --长按tips
        if not self.startTime then
            return
        end
        self.duleTime = app.session:getServerTime() or app:getUTCTime()
        if self.duleTime-self.startTime > Constant.BattleCancelInterval and not self.bShowTips then
            self.bShowTips = true
            local param = {tipsType = Enums.TipsType.classSkill,dataTemp = self, closeCallBack = function() app:dispatchCustomEvent("EVENT_CLOSE_FLOAT") end}
            app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=param})
        end
    end
end

function SkillButton:loadSkillAppearance()
    if self.classSkillId and self.classSkillId ~= 0 then
        local classSkill = GD:getClassSkill(self.classSkillId)
        if classSkill then
            self.classSkill = classSkill
            self.icon = Res.skillIconPath..classSkill.icon..".png"
            self.name = L(classSkill.name)
            self.desc = L(classSkill.des)
        end
    else
        if self.skillCfg:getIcon() ~= "" then
            self.icon = Res.skillIconPath..self.skillCfg:getIcon()..".png"
        else
            self.icon = ""
        end
        self.name = L(self.skillCfg:getName())
--        self.desc = L(self.skillCfg:getDesc())
    end

    if self.icon then
        self.mSkillIcon:loadTexture(self.icon)
    end

    self.cd = 0
end

function SkillButton:setRestrictedEffects(restrictedEffects)
    self.restrictedEffectsNode:setVisible(false)
    for i,v in ipairs(restrictedEffects) do
        if v == Enums.BuffEffectsLogic.BE_Silence then
            self.restrictedEffectsNode:setVisible(true)
        elseif v == Enums.BuffEffectsLogic.BE_Stune then
            self.restrictedEffectsNode:setVisible(true)
        end
    end
end

function SkillButton:scheduleOnce(action,delay)
    local actions = {}
    if delay then
        table.insert(actions,cc.DelayTime:create(delay))
    end
    table.insert(actions,action)
    local newAction = cc.Sequence:create(actions)
    self.scheduler:runAction(newAction)
end

function SkillButton:canPlayRlsEffectUntil(delay)
    if not self.inRleaseEffect then
        self.inRleaseEffect = true
    else
        return
    end
    local actions = {}
    local action = cc.CallFunc:create(function()
                self:playRleaseEffect()
            end)
    table.insert(actions,action)
    if delay then
        table.insert(actions,cc.DelayTime:create(delay))
    end
    local actionEnd = cc.CallFunc:create(function()
                self.inRleaseEffect = false
            end)
    table.insert(actions,actionEnd)
    local newAction = cc.Sequence:create(actions)
    self.scheduler:runAction(newAction)
end

function SkillButton:setSkillCD(cd,cdD)
    if cd and cd > 0 then
        self.mCdNode:setVisible(true)
        self.mCdNum:setString(string.format("%.1f", cd/1000))
        local percent = cd/cdD
        self.cdSprite:setPercentage(100*percent)

        if cd == 100 then
            local action = cc.CallFunc:create(function()
                self:playOnGoing()
            end)
            self:scheduleOnce(action,0.1)
        end
    else
        self.mCdNode:setVisible(false)
    end
end

function SkillButton:setButtonState(alive, restrictedEffects, isPending, preReleaseFinish, cd, cdD, isDeploy, deployLeftTime, deployD,propertyCan, priorityPass, isReady,skill,subscribeSkillId,showCanBreak)
    if cc.isDead(self.root) then
        return
    end

    self.skill = skill
    local restricted = not skill:canIgnoreRestrictEffects(restrictedEffects)
    local enabled
    -- 新手战的技能受限表现逻辑调整
    if not app:isBattleGuideComp() then
        enabled = alive and cd <= 0 and propertyCan and priorityPass and (not isPending) and (self.haveStar>=self.needStar) and (not preReleaseFinish) --and isReady
    else
        enabled = alive and cd <= 0 and propertyCan and priorityPass and (not isPending) and (not restricted) and (self.haveStar>=self.needStar) and (not preReleaseFinish) --and isReady
    end
    self:setSkillEnable(enabled)

    if self.skillId==subscribeSkillId then --预约
        self.mCdNode:setVisible(false)
        self:playPreEffect()
    else
        if preReleaseFinish then
            self:setSkillCD(cdD,cdD)
            self:canPlayRlsEffectUntil(1.0)
        else
            if cc.isAlive(self.effectArmature) then
                self.effectArmature:setVisible(false)
            end
            self:setSkillCD(cd,cdD)
        end
    end
    --self.ready:setVisible(self.skillId==subscribeSkillId)

    --光环是否激活
    if self:isHaloSkill() then
        if self.skill:isHaloActive() ~= self.mIsHaloActive then
            self.mIsHaloActive = self.skill:isHaloActive()
            self:playHaloActive(self.mIsHaloActive)
        end
    end


    if restricted then
        if cd > 0 then
            self.restrictedEffectsNode:setVisible(false)
        else
            self:setRestrictedEffects(restrictedEffects)
            self.skillMove:setManualCancel(true)
            self.skillMove:setVisible(false)
        end
    else
        self.restrictedEffectsNode:setVisible(false)
        if enabled then
            self.restrictedEffectsNode:setVisible(false)
        else
            self.skillMove:setVisible(false)
            self.skillMove:cancelCalcTime()
        end
    end

    if not self.isSetCost then
        self:setCostById(self.skillId)
    end

    if not self.bBusy then
        --restrictedEffects = {3}

        self.skillMove:cancelCalcTime()
        self:setCostById(self.skillId)
        if skill:inProgress() and skill:getChannelType()==Enums.ChannelType.ChannelType_Loop then
            if not self.mSkillLoopNode then
                self:addLoopAni()
            end
            self.mSkillLoopNode:setVisible(true)
        else
            if self.mSkillLoopNode then
                self.mSkillLoopNode:setVisible(false)
            end
        end
    end

    if self.skillCfg:getCanBreakOther() then
        if showCanBreak then
            if self.lastShowCanBreak~=showCanBreak then
                if not self.lianxieEffect then
                    self.lianxieEffect = display.newArmature({path=Res.Lianxie.dir,armatureName=Res.Lianxie.name,animationName="",skeletonName=Res.Lianxie.name})
                    self.lianxieEffect:getAnimation():gotoAndPlay("lianxie1")
                    self:addChild(self.lianxieEffect)
                end
                self.lianxieEffect:setVisible(true)
            end
        else
            if self.lianxieEffect then
                self.lianxieEffect:setVisible(false)
            end
        end
    end
    self.lastShowCanBreak = showCanBreak

    if self.skillCfg:getSCore() and self.bShowCoreBonus then
        self:addSkillGuideNode()
        self.mSkillGuideNode:setVisible(true)
        self:setLocalZOrder(TAP_ZORDER)
    else
        if self.mSkillGuideNode then
            self.mSkillGuideNode:setVisible(false)
            self:setLocalZOrder(self.originalZOrder)
        end
    end
end

function SkillButton:getSkillId()
    return self.skillCfg:getId()
end

return SkillButton
